/**
 * 自定义对话框工具函数
 * 替代 uni.showModal 的现代化实现
 */

import { ref, nextTick } from 'vue'

// 全局对话框实例
let globalModal = null

/**
 * 创建并显示对话框
 * @param {Object} options 配置选项
 * @param {string} options.title 标题
 * @param {string} options.message 消息内容
 * @param {boolean} options.showCancel 是否显示取消按钮，默认true
 * @param {string} options.confirmText 确认按钮文字，默认"确定"
 * @param {string} options.cancelText 取消按钮文字，默认"取消"
 * @param {string} options.confirmColor 确认按钮颜色，默认"#007aff"
 * @param {string} options.cancelColor 取消按钮颜色，默认"#666"
 * @returns {Promise} 返回Promise，resolve表示确认，reject表示取消
 */
export const showModal = (options = {}) => {
  return new Promise((resolve, reject) => {
    const {
      title = '',
      message = '',
      showCancel = true,
      confirmText = '确定',
      cancelText = '取消',
      confirmColor = '#007aff',
      cancelColor = '#666',
      maskClosable = true
    } = options

    // 如果当前页面没有全局对话框，创建一个
    if (!globalModal) {
      console.error('请先在页面中引入 CustomModal 组件')
      // 回退到 uni.showModal
      uni.showModal({
        title,
        content: message,
        showCancel,
        confirmText,
        cancelText,
        confirmColor,
        cancelColor,
        success: (res) => {
          if (res.confirm) {
            resolve()
          } else {
            reject(new Error('用户取消'))
          }
        },
        fail: reject
      })
      return
    }

    // 设置对话框属性
    globalModal.title = title
    globalModal.message = message
    globalModal.showCancel = showCancel
    globalModal.confirmText = confirmText
    globalModal.cancelText = cancelText
    globalModal.confirmColor = confirmColor
    globalModal.cancelColor = cancelColor
    globalModal.maskClosable = maskClosable

    // 显示对话框
    globalModal.visible = true

    // 监听事件
    const onConfirm = () => {
      cleanup()
      resolve()
    }

    const onCancel = () => {
      cleanup()
      reject(new Error('用户取消'))
    }

    const cleanup = () => {
      globalModal.visible = false
      globalModal = null
    }

    // 绑定事件
    nextTick(() => {
      if (globalModal) {
        globalModal.$on('confirm', onConfirm)
        globalModal.$on('cancel', onCancel)
      }
    })
  })
}

/**
 * 显示确认对话框（只有确认按钮）
 * @param {Object} options 配置选项
 * @returns {Promise} 返回Promise
 */
export const showConfirm = (options = {}) => {
  return showModal({
    ...options,
    showCancel: false
  })
}

/**
 * 显示成功提示对话框
 * @param {string} message 消息内容
 * @param {string} title 标题，默认"成功"
 * @returns {Promise} 返回Promise
 */
export const showSuccess = (message, title = '成功') => {
  return showModal({
    title,
    message,
    showCancel: false,
    confirmText: '知道了',
    confirmColor: '#07c160'
  })
}

/**
 * 显示错误提示对话框
 * @param {string} message 消息内容
 * @param {string} title 标题，默认"错误"
 * @returns {Promise} 返回Promise
 */
export const showError = (message, title = '错误') => {
  return showModal({
    title,
    message,
    showCancel: false,
    confirmText: '知道了',
    confirmColor: '#ff3b30'
  })
}

/**
 * 设置全局对话框实例
 * @param {Object} modal 对话框组件实例
 */
export const setGlobalModal = (modal) => {
  globalModal = modal
}

/**
 * 创建对话框Hook（用于Composition API）
 */
export const useModal = () => {
  const modalRef = ref(null)
  
  const openModal = (options) => {
    if (modalRef.value) {
      return showModal({ ...options, modal: modalRef.value })
    }
    return showModal(options)
  }
  
  return {
    modalRef,
    openModal,
    showModal,
    showConfirm,
    showSuccess,
    showError
  }
}